from flask import Blueprint, render_template, current_app, request, redirect, url_for, session
from app.models import Article
from app.models import db

from datetime import datetime, timedelta
# import pytz
from sqlalchemy.sql import text

import markdown2

bp = Blueprint('main', __name__)


from flask import render_template
from flask_login import current_user





import markdown
from markdown.extensions import tables
import re
def show_progressBars():
    # 读取Markdown文件内容
    with open('../ChaselWang.github.io/source/newposts/分类/100管理/进度条.md', 'r', encoding='utf-8') as file:
        md_content = file.read()

    # 使用markdown库解析Markdown，提取表格
    html_content = markdown.markdown(md_content, extensions=[tables.TableExtension()])

    # 使用正则表达式从HTML中提取表格数据
    table_pattern = re.compile(r'<table>.*?</table>', re.DOTALL)
    table_html = table_pattern.search(html_content).group(0)

    # 提取表格中的每一行
    row_pattern = re.compile(r'<tr>(.*?)</tr>', re.DOTALL)
    rows = row_pattern.findall(table_html)

    # 处理每一行，提取名称，完成量和目标量
    progress_data = []
    for row in rows:
        columns = re.findall(r'<td>(.*?)</td>', row)
        if len(columns) == 3:  # 假设表格有三列：名称，完成量，目标量
            name, completed, target = columns
            try:
                completed = int(completed)
                target = int(target)
                progress_data.append({
                    'name': name,
                    'completed': completed,
                    'target': target,
                    # 'percentage': (completed / target) * 100 if target else 0
                })
            except ValueError:
                pass  # 忽略非数字数据

    # 渲染模板，传入进度条数据
    return progress_data


# 主页视图函数

@bp.route('/', methods=['GET'])
def home():

    articles = Article.query.order_by(Article.updated_at.desc()).all()
    article_count = Article.query.count()
    
    # for article in articles:
    #     article.updated_at= article.updated_at.strftime('%y-%m-%d %H:%M')

    user_name = current_user.username if current_user.is_authenticated else ""

    # table_data = read_markdown_table('../ChaselWang.github.io/source/newposts/分类/100管理/进度条.md')

    # 使用函数并传入Markdown文件路径
    file_path = '../ChaselWang.github.io/source/newposts/分类/100管理/进度条.md'



    progress_data = show_progressBars()
    print(progress_data)


# HP进度条
    # 设置目标日期
    target_date = datetime(2051, 6, 29)
    # 获取当前日期
    current_date = datetime.now()
    # 计算两个日期之间的差值
    delta = target_date - current_date
    # 获取天数
    days_remaining = delta.days

    # 确保天数不会超过最大值
    current_value = min(days_remaining, 18262)
    # 计算进度百分比
    progress_percentage = (current_value / 18262) * 100


    return render_template('home.html', articles=articles,article_count=article_count,user_name=user_name,progress_data=progress_data,current_value=current_value, progress_percentage=progress_percentage)







# 搜索词高亮
from markupsafe import escape
@bp.route('/search', methods=['POST'])

def search():
    articles = Article.query.order_by(Article.updated_at.desc()).all()
    search_query = request.form.get('search', '')
    search_query = escape(search_query)  # 防止XSS攻击
    matched_articles = []

    for article in articles:
        content_lower = article.content.lower()
        query_lower = search_query.lower()
        index = content_lower.find(query_lower)

        if index != -1:
            # 获取搜索词前后内容
            start_index = max(index - 50, 0)  # 显示搜索词前50个字符，如果不足则从开头开始
            end_index = index + len(query_lower) + 50  # 显示搜索词后50个字符
            snippet = article.content[start_index:end_index]

            # 高亮搜索词
            highlighted_snippet = snippet.replace(
                search_query,
                f'<span style="background-color: yellow;">{search_query}</span>'
            )

            # 将高亮后的内容片段添加到文章字典中
            article.snippet = highlighted_snippet
            matched_articles.append(article)

    return render_template('search_results.html', articles=matched_articles, search_query=search_query)





@bp.route('/add_article', methods=['POST'])
def add_article():
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        if title and content:
            new_article = Article(title=title, content=content, updated_at=datetime.utcnow())
            db.session.add(new_article)
            db.session.commit()
    return redirect(url_for('main.home'))

@bp.route('/article/<int:article_id>')
def article_detail(article_id):
    # Fetch the article from the database based on the article_id
    if f'viewed_{article_id}' not in session:
        session[f'viewed_{article_id}'] = True
        article = Article.query.get(article_id)
        # article.view_count += 1
        new_view_count = article.view_count + 1  # SQL表达式，增加view_count

# 使用db.session.execute来执行更新语句
        db.session.execute(
            text('UPDATE articles SET view_count = :new_view_count WHERE id = :id'),
            {'new_view_count': new_view_count, 'id': article_id}
        )    
        db.session.commit()
    article=Article.query.get(article_id)
    content=markdown2.markdown(article.content, extras=["tables"])
    # content = content.replace("<table>", "<table class=\"table-auto border-collapse border border-slate-400\">")
    # content = content.replace("<tr>",  "<tr class=\"bg-slate-100 font-bold\">")
    # content = content.replace("<th>", "<th class=\"border border-slate-300 px-4 py-2\">")
    # content = content.replace("<tr>",  "<tr class=\"bg-slate-100 font-bold\">")
    return render_template('article_detail.html', article=article,content=content)

@bp.route('/about')
def about():
    article=Article.query.get(53)
    content=markdown2.markdown(article.content, extras=["tables"])
    return render_template('about.html', article=article,content=content)

@bp.route('/archives')
def archives():
    # 将数据传递给模板
    article = Article.query.order_by(Article.created_at.desc()).all()
    return render_template('archives.html', article=article)



from flask import render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from . import login_manager
from .models import User

# @app.route('/')
# def home():
#     posts = Post.query.all()
#     return render_template('home.html', posts=posts)
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired

# 定义表单类
class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Login')
@bp.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()  # 创建表单实例
    # 处理表单提交的逻辑
    if form.validate_on_submit():
        if request.method == 'POST':
            username = request.form['username']
            password = request.form['password']
            user = User.query.filter_by(username=username).first()
            if user and user.check_password(password):
                login_user(user)
                return redirect(url_for('main.home'))
            else:
                flash('Invalid username or password.')
        # 登录逻辑
        pass
    # 渲染模板，并传递表单实例
    return render_template('login.html', form=form)


@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User(username=username)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('main.login'))
    return render_template('register.html')


from flask import render_template, request, redirect, url_for, flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired

# 定义表单类
class CreatePostForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired()])
    content = StringField('Content', validators=[DataRequired()])
    submit = SubmitField('Create Post')

# 创建文章视图函数
@bp.route('/create_post', methods=['GET', 'POST'])
@login_required
def create_post():
    form = CreatePostForm()  # 创建表单实例
    if form.validate_on_submit():
        # 创建文章逻辑
        new_post = Article(title=form.title.data, content=form.content.data, author=current_user)
        db.session.add(new_post)
        db.session.commit()
        flash('Your post has been created!')
        return redirect(url_for('index'))
    return render_template('create_post.html', form=form)



@bp.route('/edit_post/<int:post_id>', methods=['GET', 'POST'])
@login_required
def edit_post(post_id):
    post = Article.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    if request.method == 'POST':
        post.title = request.form['title']
        post.body = request.form['body']
        db.session.commit()
        flash('Your post has been updated!')
        return redirect(url_for('main.home'))
    return render_template('edit_post.html', post=post)


@bp.route('/delete_post/<int:post_id>')
@login_required
def delete_post(post_id):
    post = Article.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    db.session.delete(post)
    db.session.commit()
    flash('Your post has been deleted!')
    return redirect(url_for('main.home'))


@bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('main.home'))
    
    
    #文章标签
    
@bp.route('/tag/<string:tag_name>')
def tag(tag_name):
    # 查询特定标签的所有文章
    articles = Article.query.filter(Article.tags.contains(tag_name)).all()
    return render_template('tag_articles.html',  articles=articles,tag_name=tag_name)

@bp.route('/tags')
def get_titles():
    articles = Article.query.all()
    split_list = [article.tags for article in articles]
    tags = []
    for item in split_list:
        tags.extend(item.split())

    # print(tags)
    #词频
    word_freq = {}
    for word in tags:
        if word in word_freq:
            word_freq[word] += 1
        else:
            word_freq[word] = 1
    # print(type(word_freq))

    #格式转换

# 定义一个函数，基于单词生成链接
    def generate_link(word):
        # 将空格替换为点，用于链接
        return f'./tag/{word.replace(" ", ".")}' if " " in word else f'./tag/{word}'
    converted_list = [{'name': key, 'value': value,'link':generate_link(key)} for key, value in word_freq.items()]
    # print(converted_list)
    return render_template('tag_articles.html', tags=tags,converted_list=converted_list)


@bp.route('/tailwind')
def tailwind():
    return render_template('tailwindcss.html')

@bp.route('/portfolio')
def portfolio():
    return render_template('portfolio.html')

